<template>
  <div class="singer" ref="singer">
    <listview :infos = 'singers' @select="selectSinger"></listview>
    <router-view></router-view>
  </div>
</template>

<script>
import {getSingerList} from 'api/singer'
import Singer from 'common/js/singer'
import Listview from "@/base/listview/listview";
import storage from 'good-storage'
import { mapMutations } from 'vuex'

const HOT_SINGER_LEN = 10
const HOT_NAME = '热门'

export default {
name: "singer",
  components: {Listview},
  data(){
    return {
      singers: [],
      selectedSinger: null
    }
  },
  created() {
    this._getSingerList()

  },
  methods:{
    _getSingerList(){
      getSingerList().then((result)=>{
        this.singers = result.singers
      })
    },
    selectSinger(singer) {
      this.selectedSinger = singer
      this.cacheSinger(singer)
      this.$router.push({
       path: `/singerDetail/${singer.mid}`

      })
      this.setSinger(singer)

    },

    cacheSinger(singer){
      storage.session.set('__singer__', singer)

    },
    ...mapMutations({
      setSinger: 'SET_SINGER'
    }),
    _normalizeSinger(list) {
      let map = {
        hot: {
          title: HOT_NAME,
          items: []
        }
      }
      //前10条是热门
      list.forEach((item,index) =>{
        if (index < HOT_SINGER_LEN) {
          map.hot.items.push(new Singer({
            name: item.Fsinger_name,
            id: item.Fsinger_mid
          }))
        }

        const key = item.Findex
        if (!map[key]){
          map[key] = {
            title: key,
            items: []
          }
        }
        map[key].items.push(new Singer({
          name: item.Fsinger_name,
          id: item.Fsinger_mid
        }))
      })
      //拿到的数据可能不是有序  我们还要处理
      let ret = []
      let hot = []
      for (let key in map){
        let val = map[key]
        if (val.title.match(/[a-zA-Z]/)) {
          ret.push(val)
        }else if (val.title === HOT_NAME) {
          hot.push(val)
        }
      }
      //排序
      ret.sort((a,b) =>{
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)
      })
      return hot.concat(ret)
    }
  }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
.singer
  position: absolute
  top: 88px
  bottom: 0
  width: 100%

</style>
